`timescale 1ns / 1ps
/*
 Copyright 2020 Sean Xiao, jxzsxsp@qq.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

module csr_mtvec
(
    input sys_clk,

    input i_acc_dis,

    input [ 11: 0 ] i_csr_addr,
    input [ 31: 0 ] i_csr_val,
    input i_csr_wen,

    output [ 31: 0 ] o_mtvec,

    input rst_n
);
/*
o_mtvec: Machine Trap-Vector Base-Address Register  WR

MXLEN-1                  2   1 0
--------------------------------------------------
BASE[MXLEN-1:2] (WARL )   |  MODE (WAR L )
--------------------------------------------------
MXLEN-2                      2


MODE: Value Name Description
0 Direct All exceptions set pc to BASE.
1 Vectored Asynchronous interrupts set pc to BASE+4×cause.
≥2 — Reserved

*/

wire wbck_csr_wen = i_csr_wen & ( ~i_acc_dis );
//0x305 MRW o_mtvec Machine trap-handler base address.
wire sel_mtvec = ( i_csr_addr == 12'h305 );

wire wr_mtvec = sel_mtvec & i_csr_wen;
wire mtvec_ena = ( wr_mtvec & wbck_csr_wen );
wire [ 31: 0 ] mtvec_r;
wire [ 31: 0 ] mtvec_nxt = { i_csr_val[ 31: 2 ] , 2'b00 }; //Direct All exceptions set pc to BASE.

yue_dfflr #( 32 ) mtvec_dfflr ( mtvec_ena, mtvec_nxt, mtvec_r, sys_clk, rst_n );

assign o_mtvec = mtvec_r;

endmodule
